import os
import sys


class FileManager:
    def __init__(self):
        self.script = sys.argv[0] if len(sys.argv) > 0 else ""
        self._params = self._parse_args()
        self.input_file = self.get_str("file")
        self.assets_dir = self.get_str("assets", "")

    def get_output_file(self, filename):
        path = self.get_str("file")
        # 如果path是文件，取其所在目录；如果是目录则直接使用
        base_dir = os.path.dirname(path) if os.path.isfile(path) else path
        # 合并路径并标准化（处理路径分隔符等问题）
        output_file = os.path.normpath(os.path.join(base_dir, filename))
        return output_file

    def get_all_files(self, path, exts):
        result = []

        if not os.path.exists(path):
            return result

        # 统一处理扩展名格式(确保带点)
        extensions = [
            ext.lower() if ext.startswith(".") else f".{ext.lower()}" for ext in exts
        ]

        if os.path.isfile(path):
            file_ext = os.path.splitext(path)[1].lower()
            if file_ext in extensions:
                result.append(path)
        elif os.path.isdir(path):
            for root, _, files in os.walk(path):
                for file in files:
                    file_ext = os.path.splitext(file)[1].lower()
                    if file_ext in extensions:
                        result.append(os.path.join(root, file))

        return result

    def foreach_file(self, exts, callback):
        path = self.get_str("file")
        for file in self.get_all_files(path, exts):
            callback(file)

    def _parse_args(self):
        """解析 -key value 形式的参数对"""
        args = sys.argv[1:]
        params = {}
        i = 0
        while i < len(args):
            if args[i].startswith("-"):
                key = args[i].lstrip("-")
                if i + 1 < len(args) and not args[i + 1].startswith("-"):
                    params[key] = args[i + 1]
                    i += 2
                else:
                    params[key] = True  # 无值的flag参数视为True
                    i += 1
            else:
                i += 1
        return params

    def get(self, key, default=None):
        """获取原始字符串值"""
        return self._params.get(key, default)

    def get_str(self, key, default=None):
        """获取字符串值"""
        value = self.get(key, default)
        return str(value) if value is not None else None

    def get_int(self, key, default=None):
        """获取整型值"""
        value = self.get(key)
        try:
            return int(value) if value is not None else default
        except (ValueError, TypeError):
            return default

    def get_float(self, key, default=None):
        """获取浮点值"""
        value = self.get(key)
        try:
            return float(value) if value is not None else default
        except (ValueError, TypeError):
            return default

    def get_boolean(self, key, default=None):
        """获取布尔值"""
        value = self.get(key)
        if isinstance(value, bool):
            return value
        if value is None:
            return default
        value = str(value).lower()
        return value in ("true", "yes", "1")

    def __str__(self):
        return f"Script: {self.script}\nParams: {self._params}"
